package com.maduar.demo.thread.reentrant;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Description:
 *
 * @author maduar maduar@163.com
 * @date 2021-05-06 21:56
 */
public class ReentrantLockSingleton {

    // 非公平锁
//    private static Lock lock = new ReentrantLock();
//     公平锁
    private static Lock lock = new ReentrantLock(true);

    public static void test() {
        for (int i = 0; i < 2; i++) {
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName() + "获得了锁");
                TimeUnit.MICROSECONDS.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        new Thread("线程A"){
            @Override
            public void run() {
                test();
            }
        }.start();
        new Thread("线程B"){
            @Override
            public void run() {
                test();
            }
        }.start();
    }
}
